package com.ibm.cps.sql;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.factories.DataSourceFactory;
import com.ibm.util.ErrorCode;
import com.ibm.util.SchemaCache;
import com.ibm.util.exception.CPSException;

/**
 * Created by telekinesis on 6/4/15.
 */
public class StreamingSqlParser {
	private StreamingSqlParser() {}
	
	public static ArrayNode parse(ObjectNode sqlMeta, String tenantid, DataSourceFactory datasourceFactory, SchemaCache schemaCache)
			throws CPSException {
		try {
			String sql = sqlMeta.get(MessageFields.PROCESSOR_GROUP_CONTENT).asText();
			Statement exp = CCJSqlParserUtil.parse(sql);
			StreamingSqlVisitor visitor = new StreamingSqlVisitor(
					sqlMeta, tenantid, datasourceFactory, schemaCache);
			exp.accept(visitor);
			return visitor.getResultingMetaData();
		} catch (JSQLParserException e) {
			throw new CPSException(ErrorCode.PARSE_ERROR_CODE,
					"Malformed SQL statement", e);
		} catch (IllegalArgumentException conversionException) {
			conversionException.printStackTrace();
			String message = conversionException.getMessage();
			throw new CPSException(ErrorCode.PARSE_ERROR_CODE, message,
					conversionException);
		}
	}
}